<!-- @author: Fengli -->
<!-- @date: 4/30/19 -->
<!-- @desc: 首页，用于显示任务列表 -->
<template>
  <div>
    <!-- 日期选择 -->
    <el-date-picker
      v-model="selectedDate"
      type="date"
      placeholder="选择日期"
      align="center">
    </el-date-picker>
    <div class="md-layout md-gutter">
        <div class="md-layout-item">
          <md-field>
            <label for="order">排序标准</label>
            <md-select v-model="order" name="order" id="order" @md-selected="changeTasks" :disabled="!conditionActive">
              <md-option value="all">所有</md-option>
              <md-option value="u">紧急性</md-option>
              <md-option value="i">重要性</md-option>
              <md-option value="iu">紧急性、重要性</md-option>
            </md-select>
          </md-field>
        </div>
      </div>

    <md-content class="md-scrollbar" >
      <md-empty-state
        v-if="!showList"
        md-icon="free_breakfast"
        md-label="待完成任务为空">
      </md-empty-state>
      <md-list v-if="showList" class="md-triple-line">
        <li v-for="(task,index) in tasks" :key="task.id">
          <md-list-item :to="{name:'task',params:{id:task.id}}">
            <md-avatar>
              <!--<img src="https://placeimg.com/40/40/people/1" alt="People">-->
              {{index+1}}
            </md-avatar>

            <div class="md-list-item-text">
              <span>{{task.content}}</span>
              <span>
                开始时间：{{task.startTime}}
                结束时间：{{task.endTime}}
              </span>
              <p>{{task.content}} ({{task.startTime}} - {{task.endTime}})</p>
            </div>

            <div>
              <!--这里阻止事件冒泡（在router-link里面）要用.prevent，而不是.stop-->
              <md-button class="md-icon-button md-list-action" @click.prevent="deleteTask(task.id)">
                <md-icon class="md-primary">delete</md-icon>
              </md-button>
              <md-button class="md-icon-button md-list-action" v-on:click.prevent="doneTask(task.id)">
                <md-icon class="md-primary">done</md-icon>
              </md-button>
            </div>
          </md-list-item>
          <md-divider class="md-inset"></md-divider>
        </li>
      </md-list>
    </md-content>


    <md-button class="md-fab md-primary md-fab-bottom-right"  to="/task">
      <md-icon>add</md-icon>
    </md-button>
    <!-- 确认框 -->
    <Confirm ref="confirm" :request="request" @onCancel="onCancel" @onConfirm="onConfirm"></Confirm>
    <!-- 提示框-->
    <Message ref="mes"></Message>
  </div>
</template>

<script>
  import {queryAllTasks, doneTask, deleteTask, queryTasksByCondition, queryTaskById} from '@/util/service/TaskService'
  import Confirm from '@/components/Confirm'
  import Message from '@/components/Message'
  import axios from 'axios/index'
  let now = new Date()
  export default {
    name: 'home',
    components: {
      Confirm,
      Message
    },
    data: () => ({
      selectedDate: now,
      order: 'u',
      showList: false,
      tasks: [],
      request: {
      }
    }),
    computed: {
      conditionActive () {
        if (this.selectedDate === null || this.selectedDate === undefined) {
          return false
        } else {
          return true
        }
      }
    },
    methods: {
      changeTasks () {
        let condition = {order: this.order, day: this.selectedDate}
        // 根据不同条件获取tasks
        queryTasksByCondition(condition).then((response) => {
          if (response === null || response === undefined || response.length === 0) {
            this.showList = false
          } else {
            this.tasks = response
            this.showList = true
          }
        }).catch((error) => {
          this.$refs.mes.message({content: '获取本地任务异常！', position: 'center', showMsg: true})
          throw error
        })
      },
      // 所有TaskList
      getTaskList () {
        queryAllTasks().then((response) => {
          this.tasks = response
        }).catch((erorr) => {
          // 提示查询异常信息
          this.$refs.mes.message({content: '获取所有任务异常！', position: 'center', showMsg: true})
          throw erorr
        })
      },
      // 完成任务,注意此方法和TaskService里面的doneTask不一样
      doneTask (id) {
        //  弹出确认完成任务提示框
        this.$refs.confirm.setConfirm({
          active: true,
          value: null,
          title: '删除',
          content: '确定' + '完成该任务？',
          confirmText: '确认',
          cancelText: '取消',
          data: id,
          type: 'done'
        })
      },
      // 删除任务
      deleteTask (id) {
        //  弹出确认删除框
        this.$refs.confirm.setConfirm({
          active: true,
          value: null,
          title: '删除',
          content: '确定' + '删除任务？',
          confirmText: '确认',
          cancelText: '取消',
          data: id,
          type: 'delete'
        })
      },
      onConfirm (setting) {
        // 判断类型
        if (setting.type === 'delete') {
          this.confirmDelete(setting.data)
        } else if (setting.type === 'done') {
          this.confirmDone(setting.data)
        }
      },
      onCancel (setting) {
        // todo 姑且什么都不做
      },
      confirmDone (id) {
        var that = this
        var taskId = id
        doneTask(id).then((response) => {
          //  显示操作成功
          that.$refs.mes.message({content: '恭喜你，今天已经完成一项任务', position: 'center', showMsg: true})
          //  后台同步
          queryTaskById(taskId).then((response) => {
            let token = JSON.parse(localStorage.getItem('token'))
            axios({
              method: 'post',
              data: response,
              url: that.GLOBAL.prefix + '/updateTask',
              headers: {
                Authorization: token.token_type + ' ' + token.access_token,
                contentType: 'application/json'
              }
            }).catch((error) => {
              throw error
            })
          })
          // 重新为tasks赋值
          that.changeTasks()
        }).catch((error) => {
          //  显示挫操作异常
          that.$refs.mes.message({content: '由于异常原因，任务完成失败', position: 'center', showMsg: true})
          throw error
        })
      },
      confirmDelete (id) {
        let that = this
        let taskId = id
        deleteTask(id).then((response) => {
          //  显示操作成功
          that.$refs.mes.message({content: '删除任务成功', position: 'center', showMsg: true})
          // 后台同步
          queryTaskById(taskId).then((response) => {
            let token = JSON.parse(localStorage.getItem('token'))
            axios({
              method: 'post',
              data: response,
              url: this.GLOBAL.prefix + '/updateTask',
              headers: {
                Authorization: token.token_type + ' ' + token.access_token
              }
            }).catch((error) => {
              throw error
            })
          })
          // 重新为tasks赋值
          that.changeTasks()
        }).catch((error) => {
          //  显示挫操作异常
          that.$refs.mes.message({content: '由于异常原因，任务删除失败', position: 'center', showMsg: true})
          throw error
        })
      }
    },
    mounted () {
      // 为tasks赋值
      this.changeTasks()
    }
  }
</script>

<style lang="less" scoped>
  .md-content {
    height: 500px;
    overflow: auto;
  }
  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 100%;
  }
</style>


